<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/paper-tabs/paper-tabs.html">
<link rel="import" href="../../bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="../../bower_components/iron-signals/iron-signals.html">
<link rel="import" href="../../bower_components/paper-material/paper-material.html">
<link rel="import" href="../../bower_components/neon-animation/neon-animations.html">
<link rel="import" href="../../bower_components/iron-collapse/iron-collapse.html">
<link rel="import" href="../resizable-tab-pages/resizable-tab-pages.html">
<link rel="import" href="../genemo-styles.html">
<dom-module id="genemo-tab-cards">
  <template>
    <style include="genemo-shared-styles">
		:host {
			display: block;
			font-family: 'Roboto', Arial, Helvetica, sans-serif;
			background: var(--card-background-color);
			margin: 0.6em 0;
		/*	border: #757575 solid 1px;
			border: rgba(0, 0, 0, .54) solid 1px;
		*/}
		
		.hidden {
			display: none;
		}
		
		.vertCenterContainer > div > paper-tabs {
			width: auto;
			height: 3em;
			vertical-align: bottom;
			padding: 0px;
			margin: 0px;
		}
		
		#mainCollapse {
			overflow: hidden;
			padding: 0;
		}
		
		#loadingBlock.unReady {
			display: block;
			position: absolute;
			left: 0px;
			right: 0px;
			top: 0px;
			bottom: 0px;
			opacity: 0.8;
			z-index: 1;
		}
		
		#loadingBlock {
			display: none;
		}
		
		paper-spinner {
			position: absolute;
			top: 50%;
			margin-top: -12px;
			height: 24px;
		}

	</style>
    <iron-signals on-iron-signal-collapse="collapseSignal"></iron-signals>
    <paper-material elevation="1">
      <div id="loadingBlock" class="unReady">
        <paper-spinner id="loadingSpinner" alt="Loading card content"></paper-spinner>
      </div>
      <div class="hidden">
        <content id="tabHeader" select="[tabHeader]"></content>
      </div>
      <div class="cardContent">
        <div id="cardHeader" class="clearFix genemoHeader vertCenterContainer">
          <paper-icon-button icon="{{expandIcon}}" class="leftFloat" id="expandButton" on-click="toggleCollapse"></paper-icon-button>
          <div id="cardHeadContent" class="vertCenterElement">
            <paper-tabs id="mainTab" selected="{{selectedTab}}" noink></paper-tabs>
          </div>
        </div>
        <iron-collapse id="mainCollapse" opened="{{isOpened}}" allowOverflow>
          <div>
            <resizable-tab-pages id="mainPage" selected="{{selectedTab}}" greater-entry-animation="slide-from-right-animation" greater-exit-animation="slide-left-animation" lesser-entry-animation="slide-from-left-animation" lesser-exit-animation="slide-right-animation">
              <content id="tabContent" select="[tabContent]"></content>
            </resizable-tab-pages>
          </div>
        </iron-collapse>
      </div>
    </paper-material>
  </template>
  <script>
    Polymer({
        
		is: "genemo-tab-cards",
		
		properties: {
			
			// ************* Genemo-card components **************
			isOpened: {
				type: Boolean,
				value: true,
				reflectToAttribute: true,
				observer: 'isOpenedChanged'
			},
			collapseGroup: {
				type: String,
				value: ''
			},
			collapseHeaderEl: {
				type: String,
				value: null
			},
			enableSignal: {
				type: Boolean,
				value: true
			},
			expandIcon: {
				type: String,
				value: 'expand-less'
			},
			
			domReady: {
				type: Boolean,
				value: false,
				readOnly: true,
			},
			
			ready: {
				type: Boolean,
				value: false,
				readOnly: true,
			},
			
			// ************* Tab-cards unique components *************		
			selectedTab: {
				type: Number,
				value: 0
			},
			
			pages: {
				type: Array,
				value: function() {
					return [];
				}
			},
			
			tabs: {
				type: Array,
				value: function() {
					return [];
				}
			}
		},
		
		listeners: {
			'content-dom-ready': 'contentDOMReady',
			'content-ready': 'contentReady',
		},
		
		toggleCollapseHeader: function(flag) {
			// the top node with GenemoBody should have a member function getShrunk()
			// then use the returned DOM to replace GenemoShrunk
			// if nothing, then GenemoShrunk is simply GenemoHead
			// flag is the target status
			
			if(flag && this.collapseHeaderEl) {
				// there is old collapseHeader, needs to be removed
				Polymer.dom(this.$.cardHeader).removeChild(this.collapseHeaderEl);
				this.$.cardHeadContent.classList.remove('hidden');
			} else if(!flag) {
				this.collapseHeaderEl = this.getCollapse();
				if(this.collapseHeaderEl) {
					this.$.cardHeadContent.classList.add('hidden');
					Polymer.dom(this.$.cardHeader).appendChild(this.collapseHeaderEl);
				}
			}
		},
		
		isOpenedChanged: function(newValue, oldValue) {
			this.enableSignal = false;
			if(newValue) {
				// un-collapse, send signal for all collapse groups
				this.fire('iron-signal', {name: 'collapse', data: {flag: false, group: this.collapseGroup}});
			}
			this.expandIcon = newValue? 'expand-less': 'expand-more';
			this.toggleCollapseHeader(newValue);
			this.enableSignal = true;
		},
		
		collapseSignal: function(e, detail) {
			if(this.enableSignal && this.collapseGroup == detail.group && this.isOpened != detail.flag) {
				this.isOpened = detail.flag;
			}
		},
		
		toggleCollapse: function() {
			// hide GenemoBody and convert GenemoHead to GenemoCollapse (if any)
			this.isOpened = !this.isOpened;
		},
		
 		getCollapse: function() {
			if(this.pages[this.selectedTab]) {
				if(this.pages[this.selectedTab].getCollapse && this.pages[this.selectedTab].getCollapse()) {
					return this.pages[this.selectedTab].getCollapse();
				} else if(this.pages[this.selectedTab].getExpandedHeader) {
					return this.pages[this.selectedTab].getExpandedHeader();
				}
			}
			return null;
		},
		
		populateDOM: function() {
			// populate tabs and animated pages
			
			this.pages = Polymer.dom(this.$.tabContent).getDistributedNodes();
			this.tabs = Polymer.dom(this.$.tabHeader).getDistributedNodes();
			
			while(Polymer.dom(this.$.mainTab).firstChild) {
				Polymer.dom(this.$.mainTab).removeChild(Polymer.dom(this.$.mainTab).firstChild);
			}
			
			if(this.tabs.length <= 0) {
				this.tabs = [];
				for(var i = 0; i < this.pages.length; i++) {
					if(this.pages[i].getTabHeader) {
						this.tabs.push(this.pages[i].getTabHeader());
					} else if(this.pages[i].getExpandedHeader) {
						this.tabs.push(this.pages[i].getExpandedHeader());
					}
				}
			}
			
			for(var i = 0; i < this.tabs.length; i++) {
				var newTab = document.createElement('paper-tab');
				Polymer.dom(newTab).appendChild(this.tabs[i]);
				Polymer.dom(this.$.mainTab).appendChild(newTab);
			}
			
		},
		
		contentDOMReady: function(e) {
			if(this.domReady !== e.detail.flag) {
				if(e.detail.flag) {
					// this will only happen if this.domReady !== true
					var contentNode = Polymer.dom(this.$.tabContent).getDistributedNodes(), nodeArray = [];
					if(contentNode) {
						nodeArray = Array.prototype.slice.call(contentNode);
					}
					if(nodeArray.every(function(node, index) {
						if(node.isDOMReady) {
							return node.isDOMReady();
						}
						return true;
					}, this)) {
						this.populateDOM();
						this._setDomReady(true);
					} else {
						// stop event from bubbling if status not the same as the one in the event
						e.preventDefault();
					}
				} else {
					this._setDomReady(false);
				}
			}
			return this.domReady;
		},
		
		setCardReady: function(readiness) {
			if(readiness) {
				// if card is not ready, use paper-spinner and add "unReady" class to cardContent
				this.$.loadingSpinner.active = false;
				this.$.loadingBlock.classList.remove('unReady');
			} else {
				// otherwise, deactivate paper-spinner and remove "unReady" class
				this.$.loadingBlock.classList.add('unReady');
				this.$.loadingSpinner.active = true;
			}
			this._setReady(readiness);
		},
		
		contentReady: function(e) {
			if(this.ready !== e.detail.flag) {
				if(e.detail.flag) {
					// set Ready = true, this will only happen if this.domReady !== true
					var contentNode = Polymer.dom(this.$.tabContent).getDistributedNodes(), nodeArray = [];
					if(contentNode) {
						nodeArray = Array.prototype.slice.call(contentNode);
					}
					if(nodeArray.every(function(node, index) {
						if(node.isReady) {
							return node.isReady();
						}
						return true;
					}, this)) {
						this.setCardReady(true);
					} else {
						// stop event from bubbling if status not the same as the one in the event
						e.preventDefault();
					}
				} else {
					this.setCardReady(false);
				}
			}
			return this.ready;
		},
		
		attached: function() {
			this.async(function() {
				this.contentDOMReady({detail: {flag: true}}) && this.contentReady({detail: {flag: true}});
			});
		},
		
    });
  </script>
</dom-module>
